package com.panopset.db;

import java.io.StringWriter;
import java.util.Collections;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

/**
 * SQL statement and parameters.
 * @author Karl Dinwiddie
 *
 */
public final class SqlSpec {

    /**
     * SQL parameters.
     */
    private Map<Integer, Object> params;

    /**
     *
     * @return SQL parameters.
     */
    public Map<Integer, Object> getParams() {
        if (params == null) {
            params = Collections
                    .synchronizedSortedMap(new TreeMap<Integer, Object>());
        }
        return params;
    }

    /**
     * @param sqlString SQL String.
     */
    public SqlSpec(final String sqlString) {
        sql = sqlString;
    }

    /**
     * SQL statement.
     */
    private final String sql;

    /**
     * @param i Increment starts with 1, not 0.
     * @param o Parameter value.
     */
    private void add(final Integer i, final Object o) {
        getParams().put(i, o);
    }

    /**
     * @return SQL.
     */
    public String getSql() {
        return sql;
    }

    /**
     * Set Parameter.
     * @param i Parameter sequence starts with 1, not 0.
     * @param o Parameter value.
     */
    public void setObject(final int i, final Object o) {
        add(i, o);
    }

    /**
     * Set long parameter value.
     * @param i Parameter sequence starts with 1, not 0.
     * @param value Long parameter value to set.
     */
    public void setLong(final int i, final long value) {
        add(i, value);
    }

    @Override
    public String toString() {
        StringWriter sw = new StringWriter();
        for (Entry<Integer, Object> es : getParams().entrySet()) {
            sw.append("param ");
            sw.append("" + es.getKey());
            sw.append(": ");
            if (es.getValue() == null) {
            	sw.append("null");
            } else {
                sw.append(es.getValue().toString());
            }
            sw.append("\n");
        }
        sw.append(sql);
        return sw.toString();
    }
}
